import React, { useState, useEffect } from 'react'

export default function Counter() {
  const [count, setCount] = useState(1);
  const [doubleC, setDoubleC] = useState(() => {
    // 初始化的时候需要经过复杂运算才能得到结果
    const num = count * 2;
    return num
  })

  const add = () => {
    // setCount(count + 1)
    // 接收函数
    setCount((preState) => {
      return preState + 1
    })
  }

  const addMore = () => {
    // setCount(count + 1);
    // setCount(count + 1);
    // setCount(count + 1);
    // 结果只加了 1

    setCount((preState) => {
      return preState + 1
    })
    setCount((preState) => {
      return preState + 1
    })
    setCount((preState) => {
      return preState + 1
    })
    // 结果加了 3 次
  }

  const [user, setUser] = useState({
    name: 'jack',
    age: 18
  })
  const onChangeAge = () => {
    setUser({
      ...user,
      age: 20
    })
  }

  // 生命周期
  useEffect(() => {
    console.log('Counter');
    const timer = setInterval(() => console.log(Date.now()), 1000)

    return () => {
      console.log('useEffect 回调函数的返回值函数');

      // 组件卸载之后需要干掉计时器
      clearInterval(timer)
    }
  });

  return (
    <div>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button disabled>{count}</button>
      <button>useState接受函数的情况：{doubleC}</button>
      <button onClick={add}>+</button>
      <button onClick={addMore}>连续调用 setCount</button>

      <p>
        姓名：{user.name},
        年龄：{user.age}
        <button onClick={onChangeAge}>修改年龄</button>
      </p>
    </div>
  )
}
